<template>
  <view class="components-form">
    
    <!-- 顶部自定义导航 -->
    <tn-nav-bar fixed>Form表单</tn-nav-bar>
    
    <!-- 页面内容 -->
    <view :style="{paddingTop: vuex_custom_bar_height + 'px'}">
      
      <dynamic-demo-template ref="demoTemplate" :tips="tips" :sectionList="sectionList" :full="true" :fullWindowsScroll="true" @click="click">
        <tn-form :model="model" ref="form" :errorType="errorType" :labelPosition="labelPosition" :labelWidth="labelWidth" :labelAlign="labelAlign">
          <tn-form-item label="姓名" prop="name" leftIcon="identity" :required="true" :labelPosition="labelPosition" :labelAlign="labelAlign">
            <tn-input v-model="model.name" type="text" placeholder="请输入姓名" :border="border"></tn-input>
          </tn-form-item>
          <tn-form-item label="性别" prop="sex" :labelPosition="labelPosition" :labelAlign="labelAlign">
            <tn-input v-model="model.sex" type="select" placeholder="请选择性别" :border="border" :selectOpen="actionSheetShow" @click="actionSheetShow = true"></tn-input>
          </tn-form-item>
          <tn-form-item label="所在地区" prop="region" :labelPosition="labelPosition" :labelAlign="labelAlign">
            <tn-input v-model="model.region" type="select" placeholder="请选择所在地区" :border="border" :selectOpen="pickerShow" @click="pickerShow = true"></tn-input>
          </tn-form-item>
        </tn-form>
        <view class="agreement">
          <tn-checkbox v-model="model.agreement" @change="agreementCheckChange"></tn-checkbox>
          <view class="agreement-text">勾选同意当前协议</view>
        </view>
        <tn-button backgroundColor="#01BEFF" fontColor="#FFFFFF" width="100%" @click="submit">提交</tn-button>
      </dynamic-demo-template>
      <!-- picker -->
      <tn-picker
        v-model="show"
        :mode="mode"
        :params="params"
        :range="range"
        :rangeKey="rangeKey"
        :defaultSelector="defaultSelector"
        :showTimeTag="showTimeTag"
        :startYear="startYear"
        :endYear="endYear"
        :defaultTime="defaultTime"
        :defaultRegin="defaultRegion"
        :areaCode="areaCode"
        :maskCloseable="maskCloseable"
        @cancel="cancelPicker"
        @confirm="confirmPicker"
      >
      </tn-picker>
      <!-- 性别选项 -->
      <tn-action-sheet
        v-model="actionSheetShow"
        :list="actionSheetList"
        @click="actionSheetClick"
      ></tn-action-sheet>
      <!-- 地区picker -->
      <tn-picker
        v-model="pickerShow"
        mode="region"
        @confirm="regionPickerConfirm"
      ></tn-picker>
    </view>
    
  </view>
</template>

<script>
  import dynamicDemoTemplate from '@/libs/components/dynamic-demo-template.vue'
  export default {
    name: 'componentsForm',
    components: {dynamicDemoTemplate},
    data() {
      return {
        errorType: ['message','border-bottom','toast'],
        labelPosition: 'left',
        labelAlign: 'right',
        border: false,
        actionSheetShow: false,
        labelWidth: 140,
        pickerShow: false,
        actionSheetList:[
          {
            text: '男'
          },
          {
            text: '女'
          },
          {
            text: '保密'
          }
        ],
        model: {
          name: '',
          sex: '',
          phone: '',
          desc: '',
          password: '',
          rePassword: '',
          region: '',
          goodsType: '',
          code: '',
          remember: false,
          photo: [],
          agreement: false
        },
		result: 'Picker结果',
		show: false,
		mode: 'selector',
		params: {
		  year: true,
		  month: true,
		  day: true,
		  hour: false,
		  minute: false,
		  second: false,
		  province: true,
		  city: true,
		  area: true,
		  timestamp: true
		},
		showTimeTag: false,
		startYear: 2000,
		endYear: 2100,
		defaultTime: '2021/10/01 12:00:00',
        rules: {
          name: [
            {
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
            	min: 3,
            	max: 5,
            	message: '姓名长度在3到5个字符',
            	trigger: ['change','blur'],
            },
            {
            	// 此为同步验证，可以直接返回true或者false，如果是异步验证，稍微不同，见下方说明
            	validator: (rule, value, callback) => {
            		return this.$tn.test.chinese(value);
            	},
            	message: '姓名必须为中文',
            	// 触发器可以同时用blur和change，二者之间用英文逗号隔开
            	trigger: ['change','blur'],
            },
            {
            	// 异步验证需要通过调用callback()，并且在里面抛出new Error()
            	// 抛出的内容为需要提示的信息，和其他方式的message属性的提示一样
            	asyncValidator: (rule, value, callback) => {
                if (value === '图鸟') {
                  callback(new Error('姓名重复'));
                } else {
                  // 没有错误，也要执行callback()回调
                  callback();
                }
            	},
              trigger: ['blur'],
            }
          ],
          sex: [
          	{
          		required: true,
          		message: '请选择性别',
          		trigger: 'change'
          	}
          ],
          region: [
            {
              required: true,
              message: '所在地区不能为空',
              trigger: 'change'
            }
          ],
          remember: [
            {
              required: true,
              message: '记住密码不能为空',
              trigger: 'change'
            }
          ],
        },
		sectionList: [
		  {
		    name: '参数切换',
		    section: [
		      {
		        title: '模式',
		        optional: ['单列','多列','时间','地区'],
		        methods: 'modeChange'
		      },
		      {
		        title: '显示时分秒',
		        optional: ['隐藏','显示'],
		        methods: 'timeSecondChange',
		        show: false
		      }
		    ]
		  }
		],
        tips: ['无需依赖额外的样式文件','使用tn-toast组件']
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      click(event) {
        this[event.methods] && this[event.methods](event)
      },
	  // 弹出Picker
	  showPicker(event) {
	    this.openPicker()
	  },
	  // 切换模式
	  modeChange(event) {
	    switch(event.index) {
	      case 0:
	        this.mode = 'selector'
	        this.range = ['哆啦A梦','大熊','小夫','静香','胖虎']
	        this.defaultSelector = [0]
	        this.rangeKey = ''
	        this.$refs.demoTemplate.updateSectionBtnsState([1,2,3,4], false)
	        this.$refs.demoTemplate.updateSectionBtnsState(5, false)
	        break
	      case 1:
	        this.mode = 'multiSelector'
	        this.range = [
	          [
	            {
	              id: 1,
	              name: '哆啦A梦'
	            },
	            {
	              id: 2,
	              name: '大熊'
	            },
	            {
	              id: 3,
	              name: '小夫'
	            },
	            {
	              id: 4,
	              name: '静香'
	            },
	            {
	              id: 5,
	              name: '胖虎'
	            },
	          ],
	          [
	            {
	              id: 1,
	              name: '家'
	            },
	            {
	              id: 2,
	              name: '学校'
	            },
	            {
	              id: 3,
	              name: '操场'
	            }
	          ]
	        ]
	        this.defaultSelector = [0,0]
	        this.rangeKey = 'name'
	        this.$refs.demoTemplate.updateSectionBtnsState([1,2,3,4], false)
	        this.$refs.demoTemplate.updateSectionBtnsState(5, false)
	        break
	      case 2:
	        this.mode = 'time'
	        this.$refs.demoTemplate.updateSectionBtnsState([1,2,3,4], true)
	        this.$refs.demoTemplate.updateSectionBtnsState(5, false)
	        break
	      case 3:
	        this.mode = 'region'
	        this.$refs.demoTemplate.updateSectionBtnsState([1,2,3,4], false)
	        this.$refs.demoTemplate.updateSectionBtnsState(5, true)
	        break
	    }
	    this.openPicker()
	  },
	  // 切换显示时分秒
	  timeSecondChange(event) {
	    this.params = {
	      year: true,
	      month: true,
	      day: true,
	      hour: true,
	      minute: true,
	      second: true,
	      province: true,
	      city: true,
	      area: true,
	      timestamp: true
	    }
	    this.openPicker()
	  },
      // 表单提交
      submit() {
        this.$refs.form.validate(valid => {
          if (valid) {
            // 验证通过
            if (!this.model.agreement) {
              this.$tn.message.toast('请勾选协议')
              return
            }
          } else {
            // 验证失败
          }
        })
      },
      // 点击actionSheet选择性别
      actionSheetClick(index) {
        uni.hideKeyboard()
        this.model.sex = this.actionSheetList[index].text
      },
      // 点击地区选择器
      regionPickerConfirm(event) {
        this.model.region = event.province.label + '-' + event.city.label + '-' + event.area.label
      },
	  // 打开Picker
	  openPicker() {
	    this.show = true
	  },
      // 同意协议状态修改
      agreementCheckChange(event) {
        this.model.agreement = event.value
      }
    }
  }
</script>

<style lang="scss" scoped>
  
  .agreement {
    display: flex;
    align-items: center;
    margin: 40rpx 0;
    
    &-text {
      padding-left: 8rpx;
      color: $tn-font-sub-color;
    }
  }
  .picker-result {
    margin-top: 20rpx;
    padding: 10rpx 30rpx;
    background-color: $tn-font-holder-color;
    text-align: center;
  }
  
</style>
